const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: process.env.DB_HOST || "43.143.253.188",
  port: parseInt(process.env.DB_PORT || "3306", 10),
  user: process.env.DB_USER || "nextjs",
  password: process.env.DB_PASS || "yEAiRE2jcxTyRBy5",
  database: process.env.DB_NAME || "nextjs",
  charset: 'utf8mb4',
  timezone: '+08:00',
};

async function checkMapData() {
  let connection;
  
  try {
    console.log('🔍 检查地图数据...');
    
    // 连接数据库
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功！');
    
    // 检查表是否存在
    const [tables] = await connection.execute("SHOW TABLES LIKE 'map_areas'");
    if (tables.length === 0) {
      console.log('❌ map_areas 表不存在');
      return;
    }
    
    // 查看表结构
    console.log('📋 map_areas 表结构:');
    const [columns] = await connection.execute('DESCRIBE map_areas');
    columns.forEach(col => {
      console.log(`  ${col.Field}: ${col.Type} ${col.Null === 'NO' ? 'NOT NULL' : 'NULL'} ${col.Key ? `(${col.Key})` : ''}`);
    });
    
    // 查看现有数据
    const [count] = await connection.execute('SELECT COUNT(*) as count FROM map_areas');
    console.log(`\n📊 现有地图数据: ${count[0].count} 条记录`);
    
    if (count[0].count > 0) {
      // 查看所有数据
      const [areas] = await connection.execute(`
        SELECT id, name, parent_id, extension, created_at 
        FROM map_areas 
        ORDER BY id ASC 
        LIMIT 20
      `);
      
      console.log('\n📋 地图数据示例 (前20条):');
      console.log('ID | 名称 | 父ID | 扩展信息');
      console.log('-'.repeat(60));
      areas.forEach(area => {
        console.log(`${area.id} | ${area.name} | ${area.parent_id || 'NULL'} | ${area.extension || 'NULL'}`);
      });
      
      // 按父ID分组统计
      const [parentStats] = await connection.execute(`
        SELECT 
          parent_id,
          COUNT(*) as count,
          GROUP_CONCAT(CONCAT(id, ':', name) SEPARATOR ', ') as children
        FROM map_areas 
        GROUP BY parent_id 
        ORDER BY parent_id ASC
      `);
      
      console.log('\n📈 按父ID分组统计:');
      parentStats.forEach(stat => {
        const parentName = stat.parent_id ? `父ID: ${stat.parent_id}` : '顶级区域';
        console.log(`${parentName}: ${stat.count} 个子区域`);
        console.log(`  子区域: ${stat.children}`);
      });
    }
    
  } catch (error) {
    console.error('❌ 检查过程中发生错误:', error);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 执行检查
if (require.main === module) {
  checkMapData()
    .then(() => {
      console.log('✅ 检查完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('❌ 检查失败:', error);
      process.exit(1);
    });
}

module.exports = { checkMapData };
